package com.zhjhserver.socket;

import java.nio.charset.Charset;
import org.apache.mina.core.buffer.IoBuffer;
import org.apache.mina.core.session.IoSession;
import org.apache.mina.filter.codec.CumulativeProtocolDecoder;
import org.apache.mina.filter.codec.ProtocolDecoderOutput;

import com.zhjhserver.utils.PackData;

public class ActionScriptDecoder extends CumulativeProtocolDecoder {
	public final Charset charset;

	public ActionScriptDecoder(Charset charset) {
		this.charset = charset;
	}

	@Override
	protected boolean doDecode(IoSession session, IoBuffer buffer,
			ProtocolDecoderOutput out) throws Exception {
		/*
		 * System.out.println("position：" + buffer.position());
		 * System.out.println("capacity：" + buffer.capacity());
		 * System.out.println("limit：" + buffer.limit());
		 * System.out.println("remaining：" + buffer.remaining());
		 */
		if (buffer.prefixedDataAvailable(PackData.DATA_TITLE,
				PackData.DATA_MAXIMUM)) {
			int dataLength = buffer.getInt();
			if (dataLength > 0) {
				byte[] bytes = new byte[dataLength];
				buffer.get(bytes);
				IoBuffer outBuf = IoBuffer.wrap(bytes);
				outBuf.rewind();
				PackData pkg = new PackData(outBuf);
				//System.out.println("进包：" + pkg);
				out.write(pkg);
				//System.out.println("【Limit】" + buffer.limit());
				return true;
			} else {
				System.out.println("收到客户端空数据");
			}
		}

		return false;
	}
}
